

// 后端 API 地址
const API_URL = {
    getDoctors: '/api/doctors',
    createAppointment: '/api/appointments'
};

// 全局状态
const state = {
    selectedDepartment: '心内科',
    selectedDate: '',
    selectedTime: '',
    selectedDoctor: null,
    doctors: []
};

// DOM 元素
const dateScroll = document.getElementById('dateScroll');
const departmentItems = document.querySelectorAll('.department-item');
const doctorList = document.getElementById('doctorList');
const loadingSpinner = document.getElementById('loadingSpinner');
const appointmentModal = document.getElementById('appointmentModal');
const appointmentForm = document.getElementById('appointmentForm');
const modalDoctorName = document.getElementById('modalDoctorName');
const modalDepartment = document.getElementById('modalDepartment');
const modalDate = document.getElementById('modalDate');
const modalTime = document.getElementById('modalTime');
const doctorIdInput = document.getElementById('doctorId');
const appointmentDateInput = document.getElementById('appointmentDate');
const appointmentTimeInput = document.getElementById('appointmentTime');
const symptomsInput = document.getElementById('symptoms');
const closeModalBtn = document.getElementById('closeModal');
const cancelBtn = document.getElementById('cancelBtn');
const submitBtn = document.getElementById('submitBtn');
const toast = document.getElementById('toast');

// 页面初始化
document.addEventListener('DOMContentLoaded', () => {
    generateDateOptions();
    initEventListeners();
    updateDoctorList();
    fadeInBody();
});

// 生成未来 7 天日期
function generateDateOptions() {
    const today = new Date();
    dateScroll.innerHTML = '';
    const fragment = document.createDocumentFragment();
    for (let i = 0; i < 7; i++) {
        const date = new Date(today);
        date.setDate(today.getDate() + i);
        const dateItem = document.createElement('div');
        dateItem.className = 'date-item' + (i === 0 ? ' active' : '');
        const dayLabel = document.createElement('span');
        dayLabel.className = 'day';
        dayLabel.textContent = i === 0 ? '今天' : (i === 1 ? '明天' : getWeekdayName(date.getDay()));
        const dateLabel = document.createElement('span');
        dateLabel.className = 'date';
        dateLabel.textContent = formatDate(date, 'MM/DD');
        dateItem.dataset.fullDate = formatDate(date, 'YYYY-MM-DD');
        dateItem.append(dayLabel, dateLabel);
        dateItem.addEventListener('click', () => {
            document.querySelectorAll('.date-item').forEach(item => item.classList.remove('active'));
            dateItem.classList.add('active');
            state.selectedDate = dateItem.dataset.fullDate;
            updateDoctorList();
        });
        if (i === 0) state.selectedDate = dateItem.dataset.fullDate;
        fragment.appendChild(dateItem);
    }
    dateScroll.appendChild(fragment);
}

// 事件监听
function initEventListeners() {
    // 科室选择
    departmentItems.forEach(item => {
        item.addEventListener('click', () => {
            departmentItems.forEach(d => d.classList.remove('active'));
            item.classList.add('active');
            state.selectedDepartment = item.dataset.department;
            updateDoctorList();
        });
    });
    // 关闭弹窗
    closeModalBtn.addEventListener('click', hideModal);
    cancelBtn.addEventListener('click', hideModal);
    // 提交预约
    appointmentForm.addEventListener('submit', handleAppointmentSubmit);
}

// 更新医生列表
function updateDoctorList() {
    showLoading();
    fetchDoctors().then(doctors => {
        state.doctors = doctors;
        renderDoctorList(doctors);
    }).catch(err => {
        hideLoading();
        showToast('获取医生列表失败');
        console.error(err);
    });
}

// 获取医生列表
function fetchDoctors() {
    const params = new URLSearchParams({
        department: state.selectedDepartment,
        date: state.selectedDate
    });
    return fetch(`${API_URL.getDoctors}?${params}`, { credentials: 'include' })
        .then(res => res.json())
        .then(result => {
            if (result.code === 1) return result.data;
            throw new Error(result.msg);
        });
}

// 渲染医生列表
function renderDoctorList(doctors) {
    hideLoading();
    doctorList.innerHTML = '';
    if (!doctors.length) {
        doctorList.innerHTML = '<div class="no-result"><i class="fas fa-info-circle"></i><span>没有找到符合条件的医生</span></div>';
        return;
    }
    const fragment = document.createDocumentFragment();
    doctors.forEach(doc => {
        const card = document.createElement('div');
        card.className = 'doctor-card';
        const tags = doc.specialty ? doc.specialty.split(',').map(s => `<span class="tag">${s}</span>`).join('') : '';
        card.innerHTML = `
            <img src="${doc.avatar_url || 'https://picsum.photos/100/100'}" alt="${doc.name} 头像" class="doctor-avatar">
            <div class="doctor-info">
                <h3>${doc.name}</h3>
                <p>${doc.title} | ${doc.department}</p>
                <div class="tags">${tags}</div>
                <div class="hospital-info"><i class="fas fa-hospital"></i> ${doc.hospital}</div>
            </div>
            <button class="book-btn" data-id="${doc.doctor_id}">预约</button>
        `;
        card.querySelector('.book-btn').addEventListener('click', () => showModal(doc));
        fragment.appendChild(card);
    });
    doctorList.appendChild(fragment);
}

// 显示弹窗
function showModal(doc) {
    state.selectedDoctor = doc;
    modalDoctorName.textContent = doc.name;
    modalDepartment.textContent = `${doc.department}（${doc.title}）`;
    modalDate.textContent = formatDateForDisplay(state.selectedDate);
    modalTime.textContent = state.selectedTime;
    doctorIdInput.value = doc.doctor_id;
    appointmentDateInput.value = state.selectedDate;
    appointmentTimeInput.value = state.selectedTime;
    appointmentModal.style.display = 'block';
    fadeInModal();
}

// 隐藏弹窗
function hideModal() {
    fadeOutModal(() => {
        appointmentModal.style.display = 'none';
    });
}

// 弹窗淡入动画
function fadeInModal() {
    appointmentModal.style.opacity = 0;
    appointmentModal.style.display = 'block';
    setTimeout(() => {
        appointmentModal.style.opacity = 1;
    }, 10);
}

// 弹窗淡出动画
function fadeOutModal(callback) {
    appointmentModal.style.opacity = 0;
    setTimeout(() => {
        callback();
    }, 300);
}

// 处理提交
function handleAppointmentSubmit(e) {
    e.preventDefault();
    const symptoms = symptomsInput.value.trim();
    if (!symptoms) return showToast('请简要描述您的症状');
    submitBtn.disabled = true;
    submitBtn.textContent = '预约中...';
    const data = {
        doctor_id: +doctorIdInput.value,
        appointment_date: appointmentDateInput.value,
        appointment_time: appointmentTimeInput.value,
        symptoms,
        status: '待确认'
    };
    fetch(API_URL.createAppointment, {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    }).then(r => r.json()).then(res => {
        showToast(res.code === 1 ? '预约成功' : '预约失败');
        if (res.code === 1) hideModal();
        updateDoctorList();
    }).catch(() => showToast('网络错误'))
        .finally(() => {
            submitBtn.disabled = false;
            submitBtn.textContent = '确认预约';
        });
}

// loading 和 toast
function showLoading() {
    loadingSpinner.style.display = 'block';
    doctorList.innerHTML = '';
    doctorList.appendChild(loadingSpinner);
}

function hideLoading() {
    loadingSpinner.style.display = 'none';
}

function showToast(msg) {
    toast.textContent = msg;
    toast.classList.add('show');
    setTimeout(() => toast.classList.remove('show'), 3000);
}

// 工具函数
function getWeekdayName(d) {
    return ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][d];
}

function formatDate(d, f) {
    const y = d.getFullYear(), m = ('0' + (d.getMonth() + 1)).slice(-2), day = ('0' + d.getDate()).slice(-2);
    return f === 'YYYY-MM-DD' ? `${y}-${m}-${day}` : `${m}/${day}`;
}

function formatDateForDisplay(s) {
    const d = new Date(s), w = getWeekdayName(d.getDay());
    return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日 ${w}`;
}

function fadeInBody() {
    document.body.style.opacity = 0;
    setTimeout(() => document.body.style.opacity = 1, 100);
}

// 返回按钮动画
document.querySelector('.back-btn').addEventListener('click', e => {
    e.preventDefault();
    document.body.style.opacity = 0;
    setTimeout(() => window.location.href = '/demo/index/index.html', 300);
});
